#include <iostream>
#include <cstdlib>
#include <vector>
#include <memory>
#include <pthread.h>
#include <sys/eventfd.h>
#include "Socket.hpp"
#include "Reactor.hpp"
#include "Listener.hpp"
#include "InetAddr.hpp"
#include "HandleConnection.hpp"
#include "PackpageParse.hpp"
#define EPOLL_WRITE_READ_EVENTS EPOLLIN | EPOLLET
static const std::string server_bind_ip = "0.0.0.0";

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << "<port>" << std::endl;
        return 0;
    }
    // evfd = ::eventfd(0,0);
    // pthread_t tid1;
    // pthread_create(&tid1, nullptr, Handler, (void*)argv[1]);
    uint16_t port = atoi(argv[1]);
    InetAddr addr(server_bind_ip.c_str(), port);
    PackpageParse parse;                                                                       // 报文解释器
    Listenner listener(port);                                                                  // 连接管理器
    HandleConnection handle(std::bind(&PackpageParse::Excute, &parse, std::placeholders::_1)); // IO处理器                                      // IO处理器
    std::unique_ptr<Reactor> server = std::make_unique<Reactor>();                             // 事件派发器
    server->SetOneConnection(std::bind(&Listenner::Accepter, &listener, std::placeholders::_1));
    server->SetNormalConnection( // 设置监听套接字的就绪事件处理的方法集
        std::bind(&HandleConnection::HandleRecv, &handle, std::placeholders::_1),
        std::bind(&HandleConnection::HandleSend, &handle, std::placeholders::_1),
        std::bind(&HandleConnection::HandleError, &handle, std::placeholders::_1));
    server->AddConnection(listener.Listenfd(), EPOLL_WRITE_READ_EVENTS, addr, LISTENLOCKET);
    server->Distributor();
    return 0;
}